package com.cupcorn.lib.game;

import java.io.IOException;

import com.cupcorn.lib.define.GameEngineConfiguration;
import com.cupcorn.lib.game.element.ElementSound;

import org.andengine.audio.music.Music;
import org.andengine.audio.music.MusicFactory;

public class Mfx
{
	GameEngine mainActivity;
	Music player[];
	boolean isPaused[];
	boolean supposedToBePlayed[];
	static boolean paused;
	
	public Mfx(GameEngine mainActivity, ElementSound[] CONTAINER)
	{
		player = new Music[CONTAINER.length];
		isPaused = new boolean[CONTAINER.length];
		supposedToBePlayed = new boolean[CONTAINER.length];
		paused = false;
		for(int i = 0; i < player.length; i++)
		{
			try {
				player[i] = MusicFactory.createMusicFromAsset(mainActivity.getMusicManager(), mainActivity, CONTAINER[i].getPath());
				player[i].setLooping(CONTAINER[i].isLooping());
				isPaused[i] = false;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public void play(int index)
	{
		if(!GameEngineConfiguration.use_music)return;
		paused = false;
		player[index].play();
		isPaused[index] = false;
		supposedToBePlayed[index] = true;
	}
	
	public void pause(int index)
	{
		if(!GameEngineConfiguration.use_music)return;
		paused = true;
		if(player[index].isPlaying())
		{
			player[index].pause();
			isPaused[index] = true;
		}
	}
	
	public void pauseAll()
	{
		for(int i = 0; i < player.length; i++)
		{
			if(!isPaused[i])
			{
				pause(i);
				isPaused[i] = true;
			}
		}
	}
	
	public boolean isPaused(int index)
	{
		return isPaused[index];
	}
	
	public void stop(int index)
	{
		if(!GameEngineConfiguration.use_music)return;
		paused = false;
		player[index].pause();
		supposedToBePlayed[index] = false;
	}
	
	public void resume(int index)
	{
		if(!GameEngineConfiguration.use_music)return;
		if(isPaused[index] && supposedToBePlayed[index])
		{
			isPaused[index] = false;
			player[index].play();
		}
		else
		{
			System.out.println("cannot resume music...");
		}
	}
	
	public void resumeAll()
	{
		for(int i = 0; i < player.length; i++)
		{
			resume(i);
		}
	}
}
